#pragma once

#include <iostream>
#include <pthread.h>
#include <signal.h>

#include "TcpServer.hpp"
#include "Log.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"

#define PORT 8080

class HttpServer
{
public:
    HttpServer(int port = PORT) : _port(port), _tcpServer(nullptr), _stop(false)
    {
    }

    void InitServer()
    {
        //忽略写入失败时的信号
        signal(SIGPIPE, SIG_IGN);
        _tcpServer = TcpServer::GetInstance(_port);
    }
    void Loop()
    {
        LOG(INFO, "Loop begin");

        int listenSock = _tcpServer->Sock();
        while (!_stop)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sock = accept(listenSock, (struct sockaddr *)&peer, &len);
            if (sock < 0)
            {
                continue;
            }

            //std::cout << "accept success: fd = " << (*fd) << std::endl;
            LOG(INFO, "get a new link");
            Task task(sock);
            ThreadPool::GetInstance()->PushTask(task);
        }
    }
    ~HttpServer() {}

private:
    int _port;
    TcpServer *_tcpServer;
    bool _stop;
};